package cn.spream.jstudy.designpattern.flyweight;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sjx
 * Date: 15-1-15
 * Time: 下午1:57
 * To change this template use File | Settings | File Templates.
 */
public class ConnectionPool {

    private final int poolSize = 20;
    private List<Connection> connections = new ArrayList<Connection>();
    private String url = "jdbc:mysql://localhost:3306/test";
    private String username = "root";
    private String password = "root";
    private String driverClassName = "com.mysql.jdbc.Driver";

    public ConnectionPool() throws ClassNotFoundException, SQLException {
        for (int i = 0; i < poolSize; i++) {
            Class.forName(driverClassName);
            connections.add(DriverManager.getConnection(url, username, password));
        }
    }

    public synchronized Connection getConnection() {
        Connection connection = null;
        if (connections.size() > 0) {
            connection = connections.get(0);
            connections.remove(0);
        }
        return connection;
    }

    public synchronized void release(Connection connection) {
        connections.add(connection);
    }

    public int size() {
        return connections.size();
    }

}
